import React, { Component } from 'react';
import {  Switch, Route, Link } from 'react-router-dom';
import { observer } from 'mobx-react';
import PropTypes from 'prop-types';
import NotFound from '../component/common/NotFound';
import adminStyle from './admin.scss';
import UserStore from '../store/User';
import AlStore from '../store/Alliance';

import Header from '../component/common/Header';
import LeftNav from '../component/common/LeftNav';
import Welcome from './Welcome';

import Loading from '../component/common/Loading';
import { SITE_URL } from '@/config';
const routerPath = ['house', 'contract', 'member', 'lock', 'repair', 'balance', 'finance', 'setting'];
const routerPathModule = [];
routerPath.forEach(path => {
    routerPathModule.push(require(`./${path}/routes`));
});

@observer class Admin extends Component {
    state = {
        isLogin: false
    };
    checkLogin = async () => {
        const isLogin =  await UserStore.checkLogin();
        if (!this._isMounted) return;
        if (!isLogin) {
            if (process.env.NODE_ENV === 'production') {
                window.location.href = `${SITE_URL}/login`;
            } else {
                this.props.history.push('/login');  //测试登录页面，正式版不用
            }
        } else {
            await AlStore.getInfo();
        }
        if (!this._isMounted) return;
        this.setState({ isLogin });
    };
    componentWillUnmount() {
        this._isMounted = false;
    }
    componentDidMount() {
        this._isMounted = true;
        this.checkLogin();
    }
    render() {
        const { isLogin } = this.state;
        let routes = [
            { path: '/', component: Welcome }
        ];
        routerPathModule.forEach(module => {
            const _path = module.path();
            const _pathName = module.pathName;
            routes = routes.concat(_path.map(val => ({ path: `/${_pathName}${val.path}`, component: val.component })));
        });
        const Router = routes.map((val, index) => <Route exact path={val.path} component={val.component} key={index} />);
        return (
            <div className={adminStyle['admin-wrap']}>
                <Loading loading={!isLogin}>
                    { isLogin && <Header/> }
                    { isLogin && <LeftNav/> }
                    { isLogin &&
                        <div className={adminStyle['admin-content']}>
                            <Switch>
                                {Router}
                                <Route component={NotFound}/>
                            </Switch>
                        </div>
                    }
                </Loading>
            </div>
        );
    }
}

Admin.propTypes = {
    history: PropTypes.object
};
export default Admin;